package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品(同时保存口味)
     * @param dishDTO
     */
    @Override
    @Transactional //开启数据库事务（需要启动类有相关注解）
    public void saveWithFlavor(DishDTO dishDTO) {
        /*1、向菜品表添加数据*/
        //创建Dish实体对象，复制属性
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜品表dish添加数据
        dishMapper.insert(dish);

        /*2、向菜品口味关系表添加数据*/
        //获取前端传递的菜品口味集合
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断集合是否为空
        if (flavors != null && flavors.size() > 0) {
            //获取添加数据后返回的菜品主键id
            Long dishId = dish.getId();
            //为DishFlavor对象添加获取的菜品id
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            //向口味表dish_flavor批量添加数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //查询
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        //获取总记录数与分页记录集合
        long total = page.getTotal();
        List<DishVO> result = page.getResult();
        //返回封装结果
        return new PageResult(total, result);
    }

    /**
     * 批量删除菜品(同时删除口味)
     * @param ids
     */
    @Override
    @Transactional //开启事务
    public void deleteBatch(List<Long> ids) {
        //1、启售中的菜品不能删除
        for (Long id : ids) {
            //查询出菜品信息
            Dish dish = dishMapper.selectById(id);
            //状态为启售则不能删除
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //2、被套餐关联的菜品不能删除
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3、删除菜品后，关联的口味数据也需要删除掉
        for (Long id : ids) {
            dishMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    /**
     * 根据菜品id查询菜品及相关口味
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据菜品id查询菜品数据
        Dish dish = dishMapper.selectById(id);
        //根据菜品id查询口味数据
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        //结果封装
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);
        //返回封装结果
        return dishVO;
    }

    /**
     * 修改菜品及口味
     * @param dishDTO
     */
    @Override
    @Transactional //开启数据库事务（需要启动类有相关注解）
    public void updateByIdWithFlavor(DishDTO dishDTO) {
        //创建菜品实体对象（因为需要修改公共字段）并复制属性
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品表数据
        dishMapper.updateById(dish);
        //获取菜品id
        Long dishId = dishDTO.getId();
        //因为口味修改情况有多种，所以直接删除然后重新添加
        dishFlavorMapper.deleteByDishId(dishId);
        //获取前端传递的菜品口味集合
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断集合是否为空
        if (flavors != null && flavors.size() > 0) {
            //为DishFlavor对象添加获取的菜品id
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            //向口味表dish_flavor批量添加数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据分类id查询菜品(用于新增套餐时选择菜品)
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId, String name) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .name(name)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.getByCategoryId(dish);
    }

    /**
     * 菜品起售、停售
     * @param status
     * @param id
     */
    @Override
    @Transactional //多表变更，开启事务
    public void startOrStop(Integer status, Long id) {
        //菜品停售，则包含菜品的套餐也停售。启售菜品无需考虑套餐状态。
        if (status == StatusConstant.DISABLE) {
            //1.根据菜品id查询套餐id
            List<Long> ids = new ArrayList<>();
            ids.add(id);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
            //如果存在包含该菜品的套餐,则全部停售
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
        //调用通用的更新方法，修改菜品状态
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateById(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
